package xmlfromxsd;

import com.sun.xml.internal.ws.util.Pool;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;
import javax.xml.XMLConstants;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlSeeAlso;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import org.xml.sax.SAXException;

@XmlSeeAlso(ExCoursesContainer.class)
public class XmlFromXsd {

    private static Marshaller marshaller;
    private static JAXBContext jaxbContext;
    private static SchemaFactory schemaFactory;

    public static void main(String[] args) throws JAXBException, SAXException, FileNotFoundException {

        File file = new File("course.xml");
        FileOutputStream fos = new FileOutputStream(file);

        jaxbContext = JAXBContext.newInstance(XmlFromXsd.class);
        marshaller = jaxbContext.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

        schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = schemaFactory.newSchema(new File("schema.xsd"));
        marshaller.setSchema(schema);

        ExCoursesContainer container = new ExCoursesContainer();
        List<ExCourse> list = new ArrayList<ExCourse>();
        list.add(new ExCourse(Integer.parseInt(args[0]), args[1], Float.parseFloat(args[2])));
        container.setList(list);

        marshaller.marshal(container, file);

        Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
        unmarshaller.setSchema(schema);
        ExCoursesContainer cont = (ExCoursesContainer) unmarshaller.unmarshal(file);
        System.out.println(cont.getList().get(0).toString());

    }
}
